package com.ukao.pad.ui.clothingQuery;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import com.gprinterio.GpDevice;
import com.mcxtzhang.commonadapter.rv.OnItemClickListener;
import com.ukao.pad.R;
import com.ukao.pad.adapter.OrderClothingListAdapter;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.ClothesOperateStatusBean;
import com.ukao.pad.bean.ClothingInformationBean;
import com.ukao.pad.bean.OrderInformationBean;
import com.ukao.pad.bean.ReceiptBean;
import com.ukao.pad.dialog.ClothesOperateStatusDialogFragment;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.MyOnItemClickListener;
import com.ukao.pad.presenter.OrderInformationPresenter;
import com.ukao.pad.printer.CheckPrinterHelper;
import com.ukao.pad.printer.PrinterHelper;
import com.ukao.pad.printer.PrinterReceipt;
import com.ukao.pad.usbrfidreader.UsbrfidReaderHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.OrderInformationView;
import com.ukao.pad.widget.ClearEditText;
import com.ukao.pad.widget.RecycleViewDivider;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.StateImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 订单信息界面
 */
public class OrderInformationFragment extends MvpFragment<OrderInformationPresenter> implements OrderInformationView {
    // TODO: Rename parameter arguments, choose names that match
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
   private Unbinder unbinder;
    // TODO: Rename and change types of parameters
    private String mOrderNoParam;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.print_receipt_btn)
    StateButton mPrintReceiptBtn;
    @BindView(R.id.order_input_text)
    ClearEditText mOrderInput;
    @BindView(R.id.order_search_btn)
    StateImageView orderSearchBtn;
    @BindView(R.id.order_rifd_btn)
    StateImageView orderRifdBtn;
    @BindView(R.id.shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_odd)
    TextView  tvOdd;    //单号
    @BindView(R.id.tv_clothing_status)
    TextView  tvClothingStatus;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_pay_status)
    TextView tvPayStatus;  //支付状态
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_user_name)
    TextView tvUserName; //用户姓名
    @BindView(R.id.tv_mobile_no)
    TextView tvMobileNo;
    @BindView(R.id.tv_balance)
    TextView tvUserBalance;
    @BindView(R.id.tv_user_group)
    TextView tvUserGroup;
    @BindView(R.id.tv_union_name)
    TextView tvUnionName;
    @BindView(R.id.tv_take_mode)
    TextView tvTakeMode;  //取件方式
    @BindView(R.id.tv_send_mode)
    TextView tvSendMode; //送件方式
    @BindView(R.id.order_recycler_view)
    RecyclerView MyRecyclerView;
    private OrderInformationBean  orderInformationBean;
    private OrderClothingListAdapter  orderClothingListAdapter;

    public OrderInformationFragment() {
        // Required empty public constructor
    }


    public static OrderInformationFragment newInstance(String param1, String param2) {
        OrderInformationFragment fragment = new OrderInformationFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mOrderNoParam = getArguments().getString(ARG_PARAM1);
        }
    }
    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.print_receipt_btn,R.id.order_search_btn,R.id.order_rifd_btn})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.order_search_btn:   //搜索按钮
                String  string =getText(mOrderInput);
                if(!TextUtils.isEmpty(string)){
                    super.mvpPresenter.onRequestOrderInformation(string);
                }
                break;
            case R.id.order_rifd_btn:  //
                UsbrfidReaderHelper.getInstance().readCardNum();
                break;
            case R.id.print_receipt_btn:  //打印小票
                if(orderInformationBean.getOrderId()!=-1){
                    super.mvpPresenter.printReceipt(orderInformationBean.getOrderId()+"");
                }
                break;
        }
    }

    @Override
    protected void initView() {
        //启动读卡程序
        UsbrfidReaderHelper.getInstance().readCardNum();
        super.mvpPresenter.onRequestOrderInformation(mOrderNoParam);
        UsbrfidReaderHelper.getInstance().readCardNum();
    }

    @Override
    protected OrderInformationPresenter createPresenter() {
        return new OrderInformationPresenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View  view =inflater.inflate(R.layout.fragment_order_information, container, false);
        unbinder =ButterKnife.bind(this,view);
        return view;
    }
    @Override
    protected boolean useEventBus() {
        return true;
    }


    /**
     * 布局创建好的
     * @param view
     * @param savedInstanceState
     */

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
        initAdapter();
    }

    @Override
    protected void initAdapter() {
        super.initLinearRecyclerView(MyRecyclerView);
        //添加分割线
        MyRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(),
                LinearLayoutManager.HORIZONTAL));
        List<OrderInformationBean.ProductListBean> list=new ArrayList<>();
        orderClothingListAdapter =new OrderClothingListAdapter(getActivity(),list);
        MyRecyclerView.setAdapter(orderClothingListAdapter);
        orderClothingListAdapter.setOnItemClickListener(mOnItemClick);
    }
    /**
     * 右边附件列表item 点击事件
     */
    private OnItemClickListener mOnItemClick=new MyOnItemClickListener(){
        @Override
        public void onItemClick(ViewGroup viewGroup, View view, Object o, int i) {
            super.onItemClick(viewGroup, view, o, i);
            TextView textView =(TextView)view.findViewById(R.id.tv_clothing_code);
            OrderInformationBean.ProductListBean bean=orderClothingListAdapter.getDatas().get(i);
            mvpPresenter.requestSingleClothingOperateRecord(_mActivity,String.valueOf(bean.getId()),
                    bean.getProductName(),textView.getText().toString());
        }
    };
    @Override
    protected void initListener() {
        mOrderInput.setOnEditorActionListener(mOnEditorAction);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    /**
     * 监听回车键
     */
    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                searchScanCode();
            }
            return false;
        }
    };
    /**
     * 搜索扫码的条码
     */
    private void searchScanCode(){
        String strScanCode = getText(mOrderInput);
        if (strScanCode.isEmpty()) return;
        mvpPresenter.onRequestOrderInformation(strScanCode);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        UsbrfidReaderHelper.getInstance().cancelReadCardNum();  //取消读芯片
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    @Override
    public void requestSuccess(OrderInformationBean orderInformationBean) {

        this.orderInformationBean=orderInformationBean;
             tvOdd.setText(orderInformationBean.getOrderNo());  //设置单号
            tvClothingStatus.setText(orderInformationBean.getStatusText()); //设置衣物状态
        tvMoney.setText(CheckUtils.isEmptyNumber(orderInformationBean.getPaymentPrice()));  //设置为金额
        if(orderInformationBean.getPayStatusText().equals("已支付")){
            tvPayStatus.setTextColor(Color.parseColor("#00c800"));  //绿色
            tvPayStatus.setText(orderInformationBean.getPayStatusText());
        }else {
            tvPayStatus.setTextColor(Color.parseColor("#fc5959"));  //红色
            tvPayStatus.setText(orderInformationBean.getPayStatusText());
        }
        StringBuffer  stringBuffer=new StringBuffer();
        if(orderInformationBean.getProCnt()!=0){
            stringBuffer.append(orderInformationBean.getProCnt()+"件衣服");
        }
        if(orderInformationBean.getAnnexCnt()!=0){
            stringBuffer.append(","+orderInformationBean.getAnnexCnt()+"件附件");
        }
        tvCount.setText(stringBuffer.toString());  //设置件数
        tvUserName.setText(orderInformationBean.getUserName());  //设置用户姓名

        if(!TextUtils.isEmpty(orderInformationBean.getUserPhone())){
            tvMobileNo.setText(orderInformationBean.getUserPhone());
        }else {
            tvMobileNo.setText("");
        }
        tvUserBalance.setText(CheckUtils.isEmptyNumber(orderInformationBean.getUserBalance()));  //设置用户余额
        tvUserGroup.setText(orderInformationBean.getUserGroup());  //设置用户分组情况
        if(!TextUtils.isEmpty(orderInformationBean.getUnionName())){   //设置所属集团
            tvUnionName.setText(orderInformationBean.getUnionName());
        }else {
            tvUnionName.setText("");
        }
        tvTakeMode.setText(orderInformationBean.getTakeModeText());  //设置取件方式
        tvSendMode.setText(orderInformationBean.getSendModeText());  //设置送件方式

        this.cleanCode();
        //给Adapter里面设置新数据
        orderClothingListAdapter.setDatas(this.orderInformationBean.getProductList());
    }
    /**
     * 请求焦点，清空数据
     * 隐藏软件盘
     */
    private void cleanCode() {
        mOrderInput.setText("");
        mOrderInput.requestFocus();
        KeyBoardUtil.hideInputmethod(mOrderInput);

    }
    @Subscribe()
    public void  onMessageEvent(MembershipCardEvent event){
        switch (event.getMessage()) {
            case cardNum:/*成功*/
                String rfidSecretCard = (String) event.getData();
                mOrderInput.setText(rfidSecretCard);
                searchScanCode();
                break;
        }

    }

    @Override
    public void requestFailure(String error) {
        T.show(error); //显示错误信息
        cleanCode();
    }

    @Override
    public void loadReceiptData(ReceiptBean receiptBean) {
        if (receiptBean.getOutPrintType() && CheckPrinterHelper.isReceipt()) { /*是否用热敏小票打印机*/
            PrinterReceipt mPrinterReceipt = PrinterReceipt.getInstance();
            GpDevice mDevice = new GpDevice();
            mPrinterReceipt.printGp80(receiptBean, mDevice);
        } else if (CheckPrinterHelper.isWashprinter()) {  /*打标小票*/
            PrinterHelper.getInstance().printTsc247Receipt(receiptBean);

        }
    }

    @Override
    public void receiveClothesOperateData(List<ClothesOperateStatusBean> List, String clothesName, String clothesCode) {
        ArrayList<ClothesOperateStatusBean> arrayList= (ArrayList<ClothesOperateStatusBean>) List;
        if(arrayList.size()>=1){
            ClothesOperateStatusDialogFragment cos=  ClothesOperateStatusDialogFragment.newInstance(arrayList,clothesName,clothesCode);
            cos.show(getChildFragmentManager(),cos.getClass().getName());
        }else {
            T.show("数据是null");
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
